import { sendSuccess, sendFail } from "./utils";
import { arrayToTree, buildTreeByKeys } from "./utils/routesHelper";
import {
  getAll,
  findOne,
  addData,
  updateData,
  deleteData,
} from "./utils/readFile";

export default [
  // 查找角色权限路由
  {
    url: "/api/role/routes",
    timeout: 1000,
    method: "get",
    response: (ctx) => {
      const { authorization } = ctx.headers;
      const id = authorization.slice(0, 1);
      // 查找当前用户
      const user = findOne("user", id);
      if (!user) {
        return sendFail(null, "用户不存在");
      }
      const { roles = [] } = user;
      const allRoles = getAll("role");
      // 查找角色路由
      let roleMenus = roles.reduce((cur, next) => {
        const target = allRoles.find((item) => item.roleKey === next) || {};
        cur = [...cur, ...target.checkedMenus];
        return cur;
      }, []);
      // 去除不同角色下重复路由
      roleMenus = [...new Set(roleMenus)];
      // 查找所有路由
      let list = getAll("routes");
      // 过滤获取角色路由数据
      const tree = buildTreeByKeys(list, roleMenus);
      return sendSuccess(tree);
    },
  },
  // 查找全部路由
  {
    url: "/api/system/route",
    timeout: 1000,
    method: "get",
    response: () => {
      const tree = arrayToTree(getAll("routes"));
      return sendSuccess(tree);
    },
  },
  // 添加路由,menuType:菜单类型 1目录、2菜单
  {
    url: "/api/system/route",
    timeout: 1000,
    method: "post",
    response: (ctx) => {
      // 查找路由是否已存在
      const target = findOne("routes", ctx.body.path, "path");
      if (target) {
        return sendFail(null, "菜单路由已存在");
      }
      const res = addData("routes", ctx.body);
      return sendSuccess(res.id);
    },
  },
  {
    url: "/api/system/route",
    timeout: 1000,
    method: "put",
    response: (ctx) => {
      updateData("routes", ctx.body);
      return sendSuccess();
    },
  },
  {
    url: "/api/system/route",
    timeout: 1000,
    method: "delete",
    response: (ctx) => {
      const { id } = ctx.query;
      const flag = deleteData("routes", id);
      if (!flag) {
        return sendFail(null, "路由不存在");
      }
      return sendSuccess();
    },
  },
];
